package leesoft.configuration.core;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import leesoft.configuration.databeans.DataSource;
import leesoft.configuration.interfaces.IRecordSetMapHandler;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.QueryRunner;

public class DBToolKit {
	Connection conn=null;
	
	public void open(DataSource ds){
		DbUtils.loadDriver(ds.getDriver());
		try{
			conn=DriverManager.getConnection(ds.getConnectionString(), ds.getUsername(), ds.getPassword());
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	public void open(String driver,String conn,String username,String password){
		DbUtils.loadDriver(driver);
		try{
			this.conn=DriverManager.getConnection(conn, username, password);
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
	public void close(){
		if(conn!=null){
			DbUtils.closeQuietly(conn);
		}
	}
	public void executeOn(String sql,IRecordSetMapHandler rsh){
		Statement stmt=null;
		try{
			stmt=conn.createStatement();
			ResultSet rs=stmt.executeQuery(sql);
			ResultSetMetaData rsmd=rs.getMetaData();
			int numCols=rsmd.getColumnCount();
			while(rs.next()){
				Map<String,String> rsMap=new HashMap<String,String>();
				for(int i=1;i<=numCols;i++){
					rsMap.put(rsmd.getColumnLabel(i).toLowerCase(), rs.getString(i));
				}
				if(rsh.handle(rsMap)==false){
					return;
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
